﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using Swift;
using System;

public class UI : MonoBehaviour {

	public GameObject Config;
	public InputField ServerIP;
	public InputField ServerPort;
	public Button StartGame;
	public Text Tip;

	void Start() {
		if (PlayerPrefs.HasKey ("ServerIP")) {
			ServerIP.text = PlayerPrefs.GetString ("ServerIP");
		} else {
			ServerIP.text = "127.0.0.1";
		}

		if (PlayerPrefs.HasKey ("ServerPort")) {
			ServerPort.text = PlayerPrefs.GetString ("ServerPort");
		} else {
			ServerPort.text = "5201";
		}

		DontDestroyOnLoad (GameObject.Find("Config"));
	}

	public void OnClickStart() {
		int port;
		if (int.TryParse (ServerPort.text, out port)) {

			PlayerPrefs.SetString ("ServerIP", ServerIP.text);
			PlayerPrefs.SetString ("ServerPort", ServerPort.text);

			NetCore nc = GameCore.Instance.Get<NetCore> ();
			nc.Connect2Peer (ServerIP.text, port, (conn, reason) => {

				if(conn==null) {
					Tip.text = "连接失败，原因：" + reason;
				}
				else {
					Tip.text = "连接成功";

					GameCore.Instance.SrvConn = conn;
					StartGame.enabled = false;

					MatchHelper helper = new MatchHelper();
					GameCore.Instance.Add("MatchHelper", helper);
					helper.Start( (status, msg) => {

						switch(status){
						case MatchStatus.Overtime:
							Tip.text = "匹配超时了，请重新开始游戏";
							StartGame.enabled = true;
							break;
						case MatchStatus.Matching:
							Tip.text = "正在匹配中，请稍等" + msg;
							break;
						case MatchStatus.Loading:
							Tip.text = "匹配成功了，正在加载中";
							Timer timer = GameCore.Instance.GetByName("Timer") as Timer;
							timer.AddEvent("Begin", DateTime.Now.Ticks/10000 + 2000, 0, 
								(str) => {
									Config.GetComponent<GameDriver>().GameName = helper.GameName;
									SceneManager.LoadScene("Game");
								}
							);
							break;
						}

					});
				}

			});
		} else {
			Tip.text = "端口号必须是一个整数";
		}
	}

	public void OnClickHelper() {

	}

	public void OnClickClearTip() {
		Tip.text = "";
	}

}
